package com.shuyu.gsyvideoplayer.datasource;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.danikula.videocache.HttpProxyCacheServer;
import com.danikula.videocache.ProxyCacheException;
import com.danikula.videocache.file.FileCache;

import java.io.File;
import java.io.IOException;

import tv.danmaku.ijk.media.player.misc.IMediaDataSource;

/**
 * Created by zhoulikai on 17/4/27.
 */

public class MediaDataSource implements IMediaDataSource {
    private final String TAG = "MediaDataSource";
    private String path;
    private FileCache fileCache;
    public static final String PREFIX_FLAG = "file://";

    public MediaDataSource(Context context, String path) {
        this.path = path.substring(PREFIX_FLAG.length() + 1);
        try {
            fileCache = new FileCache(new File(this.path), new HttpProxyCacheServer.Builder(context).buildConfig());
        } catch (ProxyCacheException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int readAt(long position, byte[] buffer, int offset, int size) throws IOException {

        int count = 0;
        try {
            count = fileCache.read(buffer, position, offset + size);
        } catch (ProxyCacheException e) {
            e.printStackTrace();
        }
        Log.d(TAG, ">>>>position>>>>" + position + ">>>>>>bytes>>>>>>" + buffer + ">>>>>>>>>" + offset + ">>>>count>>>>" + count + ">>>>>>" + size);
        return count;
    }

    @Override
    public long getSize() throws IOException {
        try {
            return fileCache.available();
        } catch (ProxyCacheException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void close() throws IOException {
        try {
            fileCache.close();
        } catch (ProxyCacheException e) {
            e.printStackTrace();
        }
    }
}
